package tianrun.ziguan.api.calculate.config.service.common.edit.asset;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.shiro.util.Assert;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import tianrun.ziguan.api.calculate.config.dto.request.common.DeleteBody;
import tianrun.ziguan.api.calculate.config.dto.request.common.add.edit.SaveBody;
import tianrun.ziguan.api.calculate.config.entity.TAssetUsageAnalysisModule;
import tianrun.ziguan.api.calculate.config.listener.RefreshCacheListener;
import tianrun.ziguan.api.calculate.config.service.asset.module.ITAssetUsageAnalysisModuleService;
import tianrun.ziguan.api.calculate.config.service.common.edit.AbstractDealService;
import tianrun.ziguan.api.calculate.config.service.ge.TGeTableConfigService;
import tianrun.ziguan.api.calculate.config.utils.MapUtil;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

@Service
public class AssetUsageAnalysisModuleDealService extends AbstractDealService {

    private final ITAssetUsageAnalysisModuleService usageAnalysisModuleService;


    public AssetUsageAnalysisModuleDealService(TGeTableConfigService tableConfigService, ITAssetUsageAnalysisModuleService usageAnalysisModuleService) {
        super(tableConfigService);

        this.usageAnalysisModuleService = usageAnalysisModuleService;
    }

    @Override
    public void before(SaveBody body) {
        String calLabel = MapUtil.getString(body.getData(), "cal_label");
        Long calAssetId = MapUtil.getLong(body.getRawData(), "cal_asset_id");
        LambdaQueryWrapper<TAssetUsageAnalysisModule> wrapper = Wrappers.<TAssetUsageAnalysisModule>lambdaQuery().
                eq(TAssetUsageAnalysisModule::getCalLabel, calLabel).
                eq(TAssetUsageAnalysisModule::getCalAssetId, calAssetId);
        if (Objects.equals(body.getOption(), SaveBody.Option.EDIT)) {
            wrapper.ne(TAssetUsageAnalysisModule::getId, body.getId());
        }
        int count = usageAnalysisModuleService.count(wrapper);
        Assert.isTrue(count == 0, calLabel + "已存在！");
    }


    @Override
    public String tableName() {
        return "t_asset_usage_analysis_module";
    }

    @Override
    public void after(SaveBody body) {
        RefreshCacheListener.flushByModuleId(body.getId(),tableName());
    }
    @Override
    public void delBefore(DeleteBody body) {

    }

    @Override
    public void listAfter(List<Map<String, Object>> result) {

    }

    @Override
    @Async("asyncServiceExecutor")
    public void delAfter(DeleteBody body) {
        Set<Long> ids = body.getIds();
        ids.forEach(id-> RefreshCacheListener.flushByModuleId(id,tableName()));
    }

    @Override
    public void infoAfter(Map<String, Object> bean) {

    }


}
